package login

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"gorm.io/gorm"
	"insighttracking/common/enum"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"net/http"
	"time"

	"insighttracking/apps/customer/internal/svc"
	"insighttracking/apps/customer/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type LoginApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewLoginApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *LoginApiLogic {
	hostname, _ := os.Hostname()
	return &LoginApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *LoginApiLogic) LoginApi(req *types.LoginReq) (resp *types.LoginResp, err error) {
	accountEntity, err := dao.AccountEntity.WithContext(l.ctx).Where(
		dao.AccountEntity.Username.Eq(req.Username),
		dao.AccountEntity.AccountType.Eq(enum.EnterpriseCustomerEnum),
	).First()
	if errors.Is(err, gorm.ErrRecordNotFound) {
		logx.WithContext(l.ctx).Infof("登录失败-根据用户名获取数据失败:%v", err)
		return nil, errors.New("无该账号信息，登录失败")
	}
	if accountEntity.Status == 2 {
		return nil, errors.New("该用户已禁用，请联系管理员处理")
	}
	if utils.Md5(req.Password, accountEntity.Salt) != accountEntity.Password {
		logx.WithContext(l.ctx).Infof("登录失败-账号密码错误")
		return nil, errors.New("账号或密码不正确！")
	}
	// 只有企业账号可以登录
	if !k.IsContains([]int64{enum.EnterpriseCustomerEnum}, accountEntity.AccountType) {
		logx.WithContext(l.ctx).Infof("当前账号无权限登录,当前账号类型:%v", accountEntity.AccountType)
		return nil, errors.New("当前账号无权限登录")
	}
	clientIP := utils.ClientIP(l.Request)
	resp = &types.LoginResp{
		AccountID:     accountEntity.AccountID,                                                            // 主键id
		Username:      accountEntity.Username,                                                             // 用户名
		Status:        accountEntity.Status,                                                               // 状态0表示正常,1表示禁用
		AccountType:   accountEntity.AccountType,                                                          // 账号类型,0表示超管,1表示后台运营人员,2表示企业账号,3表示门店账号
		EnterpriseID:  accountEntity.EnterpriseID,                                                         // 企业id
		CustomerID:    accountEntity.CustomerID,                                                           // 客户id
		LastLoginDate: k.If(accountEntity.LastLoginDate.IsZero(), 0, utils.TimestampToString(time.Now())), // 最后登录时间
		LastLoginIP:   clientIP,                                                                           // 最后登录ip地址
		CreatedAt:     utils.TimestampToString(accountEntity.CreatedAt),                                   // 创建时间
		UpdatedAt:     utils.TimestampToString(accountEntity.UpdatedAt),                                   // 更新时间
		//Mobile:
	}
	token, err := utils.GenerateToken(l.svcCtx.RedisDb, accountEntity.AccountID, k.MapToString(resp), "customer")
	if err != nil {
		logx.WithContext(l.ctx).Infof("登录失败-存储redis失败:%v", err.Error())
		return nil, errors.New("系统异常，情重试")
	}
	// 修改最后一次登录信息
	_, _ = dao.AccountEntity.WithContext(l.ctx).Where(dao.AccountEntity.AccountID.Eq(accountEntity.AccountID)).UpdateSimple(
		dao.AccountEntity.LastLoginDate.Value(time.Now()),
		dao.AccountEntity.LastLoginIP.Value(clientIP),
	)
	resp.Token = token
	return
}
